package com.hxkj.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxkj.service.FileService;
import com.hxkj.utils.ImageZipUtil;
import com.hxkj.utils.JsonUtils;
import com.integral.mall.file.po.SysFile;
import com.integral.mall.file.service.SysFileService;
import com.integral.mall.file.utils.file.FileUtil;
import com.platform.common.domain.exception.CustomMessageException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Service("fileService")
@Slf4j
public class FlieServiceImpl implements FileService {

    @Resource
    private SysFileService sysFileService;
    @Value("${storage.imgUrl}")
    private String imgUrl;

    @Override
    public String imgUpload(MultipartFile files, String FilePath) throws Exception {
        try {
            String filePath = upload(files, FilePath);
            if (filePath == null) {
                throw new CustomMessageException(400, "请选择合理的图片类型,仅支持:gif,jpg,jpeg,png,psd格式的图片文件");
            }
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public JSONObject ueditorimgupload(MultipartFile file, String filePath, String action) throws Exception {
        String result;
        // 判断action 是不是 congfig, 如果是就返回config.json给前端
        if (action.equals("config")) {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/config.json");
            result = JsonUtils.readFile1(inputStream);
            result.replaceAll("/\\*{1,2}[\\s\\S]*?\\*/", "");
            JSONObject json = JSONObject.parseObject(result);

            return json;
        }
        Map<String, String> map = new HashMap<>();
        try {
            // 上传图片
            String filePaths;

            JSONObject jsons = null;
            if (null != file) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                String fiName = System.currentTimeMillis() + "";
                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                if (!checkfileType(fileType)) {
                    throw new CustomMessageException(400, "不合法的文件类型");
                }
                SysFile sysFile = sysFileService.upload(fiName, fileType, filePath + "/" + FileUtil.getYMDPatternPath(), zipImage(file));
                filePaths =  imgUrl + "upload/" + sysFile.getFilePath();
                map.put("url", filePaths);
                map.put("state", "SUCCESS");
                map.put("original", fiName + fileType);
                map.put("title", fiName + fileType);
                String mapJson = JSON.toJSONString(map);
                jsons = JSONObject.parseObject(mapJson);
            }
            return jsons;

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * 普通图片上传
     *
     * @param file
     * @param filePath
     * @return
     */
    private String upload(MultipartFile file, String filePath) throws Exception {

        if (null != file) {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            String fiName = String.valueOf(System.currentTimeMillis());
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!checkfileType(fileType)) {
                throw new CustomMessageException(400, "请选择合理的图片类型,仅支持:gif,jpg,jpeg,png,psd格式的图片文件");
            }
            SysFile sysFile = sysFileService.upload(fiName, fileType, filePath + "/" + FileUtil.getYMDPatternPath(), zipImage(file));
            return imgUrl + "upload/" + sysFile.getFilePath();

        }
        throw new CustomMessageException(400, "请选择需要上传的文件");
    }

    /**
     * 判断拓展名
     *
     * @param type
     * @return
     */
    boolean checkfileType(String type) {
        String[] fileType = new String[]{"gif", "jpg", "jpeg", "bmp", "png", "psd"};
        return ArrayUtils.contains(fileType, type);
    }

    /**
     * 压缩图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    InputStream zipImage(MultipartFile file) throws Exception {
        return file.getSize() / 1024 > 100 ? ImageZipUtil.zipWidthHeightImageFile(file.getInputStream(), System.getProperty("java.io.tmpdir"), 320, 240, 10.f) : file.getInputStream();

    }
}
